package top.jnaw.jee.platform.controller.basics.extend;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import top.jnaw.jee.platform.Consts;
import top.jnaw.jee.platform.Consts.Result;
import top.jnaw.jee.platform.model.Loan;
import top.jnaw.jee.platform.model.Users;
import top.jnaw.jee.utils.ModelResult;
import top.jnaw.jee.utils.Shiros;
import top.jnaw.jee.utils.Strings;
import top.jnaw.jee.utils.wechat.Wechats;

public class ApprovalLoanController extends Controller {

  private static final String WECHAT_STATE = "loan";
  private static final String WECHAT_APP_URL =
      Consts.DOMAIN + "wechat/index.html?data=%s";

  public void index() {

    Wechats.redirect(this, WECHAT_STATE, WECHAT_APP_URL);
  }

  public void add() {
    ModelResult result = new ModelResult(Result.kBadParam);
    JSONObject req = Strings.toJSONObject(this);
    final String openid = Strings.getString(req, "openid", "");
    final String type = Strings.getString(req, "type", "natural");
    final String data = Strings.getString(req, "data", "");
    if (StrKit.notBlank(openid)) {
      result = Loan.add(openid, type, data);
    }
    renderJson(result.toJson());
  }

  public void list() {
    JSONObject req = Strings.toJSONObject(this);
    final int page = Strings.getInt(req, "page", Consts.DEFAULT_PAGE);
    final int size = Strings.getInt(req, "size", Consts.DEFAULT_PAGE_SIZE);
    final JSONArray filter = Strings.getJSONArray(req, "filter", null);
    Users user = Users.getByUsername(Shiros.getUser());
    int uid = (null != user) ? user.getId() : -1;
    renderJson(Strings
        .formatJsonDateTime(Strings.formatPage(Loan.list(page, size, filter, uid))));
  }

  public void query() {
    ModelResult result = new ModelResult(Result.kBadParam);
    JSONObject req = Strings.toJSONObject(this);
    final int id = Strings.getInt(req, "id", Consts.DEFAULT_BAD_ID);
    if (id > 0) {
      result = Loan.query(id);
    }
    renderJson(result.toJson());
  }
}
